﻿using XiangziProjectTemplete.Core.Api.Common;
using XiangziProjectTemplete.Core.Common.Helper;
using XiangziProjectTemplete.Core.Common.HttpContextUser;
using XiangziProjectTemplete.Core.Extensions.Others;
using XiangziProjectTemplete.Core.IRepository.UnitOfWork;
using XiangziProjectTemplete.Core.IServices;
using XiangziProjectTemplete.Core.IServices.XiangziProjectTemplete;
using XiangziProjectTemplete.Core.Model;
using XiangziProjectTemplete.Core.Model.CommonModel;
using XiangziProjectTemplete.Core.Model.Enums.XiangziProjectTemplete;
using XiangziProjectTemplete.Core.Model.Models;
using XiangziProjectTemplete.Core.Model.ParamModels;
using XiangziProjectTemplete.Core.Model.PostParamModels.XiangziProjectTemplete;
using XiangziProjectTemplete.Core.Model.ViewModels.XiangziProjectTemplete;
using XiangziProjectTemplete.Core.Model.Views;
using XiangziProjectTemplete.Core.Utility;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using LesCCService;

namespace XiangziProjectTemplete.Core.Api.Controllers
{
    /// <summary> 
    /// 库存信息控制器 
    /// </summary> 
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize(Permissions.Name)]
    public class Les_StockInfoController : ControllerBase
    {
        private readonly IV_BufferStockCollectGroupMaterialServices _V_BufferStockCollectGroupMaterialServices;
        private readonly ILes_PickInStockTaskServices _Les_PickInStockTaskServices;
        private readonly ILes_StockInfoServices _Les_StockInfoServices;
        private readonly IV_LES_BufferStockCollectService _v_Les_BufferStockCollectService;
        private readonly IUser _user;
        private readonly IBase_MaterialServices _base_MaterialServices;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IBase_StationServices _base_StationServices;
        private readonly ILogger<Les_StockInfoController> _logger;
        private readonly IBase_CodeItemsServices base_CodeItemsServices;
        private readonly ILes_Mater_V_StationServices _les_Mater_V_StationServices;
        private readonly ILes_ProcedureRoleServices _les_ProcedureRoleServices;
        private readonly ILes_PersonHandlerRecordServices _les_PersonHandlerRecordServices;
        private readonly ILes_AgvTaskServices _les_AgvTaskServices;
        private readonly IBase_UserStationServices _base_UserStationServices;
        private readonly IV_LES_BufferStockCollectByStationServices _v_LES_BufferStockCollectByStationServices;
        private readonly ILes_InOutStockRecordServices _les_InOutStockRecordServices;

        public Les_StockInfoController(
            ILes_InOutStockRecordServices les_InOutStockRecordServices,
            IV_LES_BufferStockCollectByStationServices v_LES_BufferStockCollectByStationServices,
            IBase_UserStationServices base_UserStationServices,
            ILes_AgvTaskServices les_AgvTaskServices,
            ILes_PersonHandlerRecordServices les_PersonHandlerRecordServices,
            IV_BufferStockCollectGroupMaterialServices V_BufferStockCollectGroupMaterialServices,
            ILes_ProcedureRoleServices les_ProcedureRoleServices,
            ILes_Mater_V_StationServices les_Mater_V_StationServices,
            ILes_PickInStockTaskServices les_PickInStockTaskServices,
        IBase_CodeItemsServices _base_CodeItemsServices,
            ILogger<Les_StockInfoController> _logger,
            IBase_StationServices base_StationServices,
            IBase_MaterialServices base_MaterialServices, ILes_StockInfoServices Les_StockInfoServices,
            IUnitOfWork unitOfWork,
            IUser user, IV_LES_BufferStockCollectService v_Les_BufferStockCollectService)
        {
            this._les_InOutStockRecordServices = les_InOutStockRecordServices;
            this._v_LES_BufferStockCollectByStationServices = v_LES_BufferStockCollectByStationServices;
            this._base_UserStationServices = base_UserStationServices;
            this._les_AgvTaskServices = les_AgvTaskServices;
            this._les_PersonHandlerRecordServices = les_PersonHandlerRecordServices;
            _V_BufferStockCollectGroupMaterialServices = V_BufferStockCollectGroupMaterialServices;
            this._les_ProcedureRoleServices = les_ProcedureRoleServices;
            _les_Mater_V_StationServices = les_Mater_V_StationServices;
            this._Les_PickInStockTaskServices = les_PickInStockTaskServices;
            this._base_MaterialServices = base_MaterialServices;
            _Les_StockInfoServices = Les_StockInfoServices;
            _user = user;
            _v_Les_BufferStockCollectService = v_Les_BufferStockCollectService;
            this._unitOfWork = unitOfWork;
            this._base_StationServices = base_StationServices;
            this._logger = _logger;
            this.base_CodeItemsServices = _base_CodeItemsServices;
        }

        /// <summary> 
        /// 分页获取汇总库存信息列表 
        /// </summary> 
        /// <param name="param">筛选条件</param> 
        /// <returns>获取结果</returns> 
        [HttpPost]
        [AllowAnonymous]
        public async Task<MessageModel<PageModel<V_LES_BufferStockCollect>>> GetCollect([FromBody] Les_StockInfoParam param)
        {
            if (string.IsNullOrEmpty(param.searchVal) || string.IsNullOrWhiteSpace(param.searchVal))
            {
                param.searchVal = string.Empty;
            }

            var whereConditions = WhereConditionsExtensions.GetWhereConditions<V_LES_BufferStockCollect, Les_StockInfoParam>(param);
            if (!whereConditions.IsSuccess)
            {
                return new MessageModel<PageModel<V_LES_BufferStockCollect>>()
                {
                    msg = whereConditions.ErrMsg,
                    success = false,
                    response = null
                };
            }

            //增加过滤，配置权限过滤
            SeeProcedureRoleViewModel seeProcedureRoleViewModel = await _les_ProcedureRoleServices.GetProcedureListByUser(_user);
            List<int> proList = new List<int>();
            if (seeProcedureRoleViewModel.IsHasAllProcedure)
            {//全部权限

            }
            else
            {//部分权限
                proList = seeProcedureRoleViewModel.ProcedureList;
                Expression<Func<V_LES_BufferStockCollect, bool>> whereExpression2 = a => a.AllowProcedure != null && proList.Contains(Convert.ToInt32(a.AllowProcedure));
                whereConditions.data = whereConditions.data.And(whereExpression2);
            }

            #region 根据用户进行过滤所能看到的站点权限
            SeeUserStationViewModel seeStationView = await _base_UserStationServices.GetSeeStationListByUser(_user);
            List<int> seeStationList = new List<int>();
            if (seeStationView != null && seeStationView.StationIdList.Count > 0)
            {
                seeStationList = seeStationView.StationIdList;
                Expression<Func<V_LES_BufferStockCollect, bool>> whereExpression2 = a => seeStationList.Contains(Convert.ToInt32(a.StationId));
                whereConditions.data = whereConditions.data.And(whereExpression2);
            }
            #endregion

            if (!string.IsNullOrEmpty(param.RequestFlag))
            {
                if (param.RequestFlag == "BufferStockMgr")
                {
                    Expression<Func<V_LES_BufferStockCollect, bool>> whereExpression2 = a => (a.StoreAreaCode == Convert.ToString(StoreAreaEnum.FJQ) || a.StoreAreaCode == Convert.ToString(StoreAreaEnum.StoreBuffer));
                    whereConditions.data = whereConditions.data.And(whereExpression2);
                }
            }


            var data = await _v_Les_BufferStockCollectService.QueryPage(whereConditions.data, param.page, param.pageSize, " InStoreTime desc ");
            return new MessageModel<PageModel<V_LES_BufferStockCollect>>()
            {
                msg = "获取成功",
                success = true,
                response = data
            };

        }


        /// <summary> 
        /// 获取指定库位区域的库存信息 
        /// </summary> 
        /// <param name="storeAreaCode">库存区域编号</param> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        //注意：必须要加权限，不然一直刷新但是token不延时 【Editby shaocx,2021-10-18】
        //[AllowAnonymous]
        public async Task<MessageModel<List<V_LES_BufferStockCollectByStation>>> GetStockByArea(string storeAreaCode)
        {
            var data = await _v_LES_BufferStockCollectByStationServices.Query(x => x.StoreAreaCode == storeAreaCode);
            foreach (var item in data)
            {
                item.Station_ModifyTimeStr = DateTimeHelper.ConvertToString(item.Station_ModifyTime);
            }
            return new MessageModel<List<V_LES_BufferStockCollectByStation>>()
            {
                msg = "获取成功",
                success = true,
                response = data.OrderBy(x => x.StationCode).ToList()
            };
        }


        /// <summary>
        /// 获取 立库缓存区库存列表，为可视化页面专用
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //注意：必须要加权限，不然一直刷新但是token不延时 【Editby shaocx,2021-10-18】
        //[AllowAnonymous]
        public async Task<MessageModel<List<BufferStockCollectByStationGroupCardViewModel>>> GetStockForBufferStockVisual()
        {
            List<BufferStockCollectByStationGroupCardViewModel> resultModelList = new List<BufferStockCollectByStationGroupCardViewModel>();
            var data = await _v_LES_BufferStockCollectByStationServices.Query(x => x.StoreAreaCode == StoreAreaEnum.StoreBuffer.ToString());
            foreach (var item in data)
            {
                item.Station_ModifyTimeStr = DateTimeHelper.ConvertToString(item.Station_ModifyTime);
            }

            List<V_LES_BufferStockCollectByStation> newList = new List<V_LES_BufferStockCollectByStation>();
            //第一排
            var _list = LesApiCommon.GetDataByRow(1, 10, data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "第一排",
                bufferStockCollectByStationList = _list
            });
            //第二排
            _list = LesApiCommon.GetDataByRow(11, 20, data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "第二排",
                bufferStockCollectByStationList = _list
            });
            //第三排
            _list = LesApiCommon.GetDataByRow(21, 30, data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "第三排",
                bufferStockCollectByStationList = _list
            });
            //第四排
            _list = LesApiCommon.GetDataByRow(31, 40, data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "第四排",
                bufferStockCollectByStationList = _list
            });
            //第五排
            _list = LesApiCommon.GetDataByRow(41, 50, data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "第五排",
                bufferStockCollectByStationList = _list
            });
            //第六排
            _list = LesApiCommon.GetDataByRow(51, 60, data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "第六排",
                bufferStockCollectByStationList = _list
            });
            //第七排
            _list = LesApiCommon.GetDataByRow(61, 70, data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "第七排",
                bufferStockCollectByStationList = _list
            });

            return new MessageModel<List<BufferStockCollectByStationGroupCardViewModel>>()
            {
                msg = "获取成功",
                success = true,
                response = resultModelList
            };
        }


        #region 低压脱模

        /// <summary>
        /// 获取 低压脱模库存列表，为可视化页面专用
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //注意：必须要加权限，不然一直刷新但是token不延时 【Editby shaocx,2021-10-18】
        //[AllowAnonymous]
        public async Task<MessageModel<List<BufferStockCollectByStationGroupCardViewModel>>> GetStockForLVDeMoldVisual()
        {
            List<BufferStockCollectByStationGroupCardViewModel> resultModelList = new List<BufferStockCollectByStationGroupCardViewModel>();
            var data = await _v_LES_BufferStockCollectByStationServices.Query(x => x.StoreAreaCode == StoreAreaEnum.KCQY_TMNWMWXCFQ.ToString());
            foreach (var item in data)
            {
                item.Station_ModifyTimeStr = DateTimeHelper.ConvertToString(item.Station_ModifyTime);
            }

            List<V_LES_BufferStockCollectByStation> newList = new List<V_LES_BufferStockCollectByStation>();
            //第一排
            var _list = LesApiCommon.GetDataByCodeFilterForLVDeMold("-A-", data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "A排",
                bufferStockCollectByStationList = _list
            });
            //第二排
            _list = LesApiCommon.GetDataByCodeFilterForLVDeMold("-B-", data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "B排",
                bufferStockCollectByStationList = _list
            });
            //第三排
            _list = LesApiCommon.GetDataByCodeFilterForLVDeMold("-C-", data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "C排",
                bufferStockCollectByStationList = _list
            });


            return new MessageModel<List<BufferStockCollectByStationGroupCardViewModel>>()
            {
                msg = "获取成功",
                success = true,
                response = resultModelList
            };
        }


        /// <summary>
        /// 获取 低压脱模托盘区列表，为可视化页面专用
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //注意：必须要加权限，不然一直刷新但是token不延时 【Editby shaocx,2021-10-18】
        [AllowAnonymous]
        public async Task<MessageModel<List<BufferStockCollectByStationGroupCardViewModel>>> GetStockForLVDeMoldPalletVisual()
        {
            List<BufferStockCollectByStationGroupCardViewModel> resultModelList = new List<BufferStockCollectByStationGroupCardViewModel>();
            var data = await _v_LES_BufferStockCollectByStationServices.Query(x => x.StoreAreaCode == StoreAreaEnum.KCQY_TMNWMKTQ.ToString());
            foreach (var item in data)
            {
                item.Station_ModifyTimeStr = DateTimeHelper.ConvertToString(item.Station_ModifyTime);
            }

            List<V_LES_BufferStockCollectByStation> newList = new List<V_LES_BufferStockCollectByStation>();
            //第一排
            var _list = LesApiCommon.GetDataByCodeFilterForLVDeMold("-D-", data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "D排",
                bufferStockCollectByStationList = _list
            });
            //第二排
            _list = LesApiCommon.GetDataByCodeFilterForLVDeMold("-E-", data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "E排",
                bufferStockCollectByStationList = _list
            });
            //第三排
            _list = LesApiCommon.GetDataByCodeFilterForLVDeMold("-F-", data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "F排",
                bufferStockCollectByStationList = _list
            });


            return new MessageModel<List<BufferStockCollectByStationGroupCardViewModel>>()
            {
                msg = "获取成功",
                success = true,
                response = resultModelList
            };
        }

        #endregion

        #region 高压脱模

        /// <summary>
        /// 获取 高压脱模库存列表，为可视化页面专用
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //注意：必须要加权限，不然一直刷新但是token不延时 【Editby shaocx,2021-10-18】
        //[AllowAnonymous]
        public async Task<MessageModel<List<BufferStockCollectByStationGroupCardViewModel>>> GetStockForHVDeMoldVisual()
        {
            List<BufferStockCollectByStationGroupCardViewModel> resultModelList = new List<BufferStockCollectByStationGroupCardViewModel>();
            var data = await _v_LES_BufferStockCollectByStationServices.Query(x => x.StoreAreaCode == StoreAreaEnum.KCQY_TMYBWXCFQ.ToString());
            foreach (var item in data)
            {
                item.Station_ModifyTimeStr = DateTimeHelper.ConvertToString(item.Station_ModifyTime);
            }

            List<V_LES_BufferStockCollectByStation> newList = new List<V_LES_BufferStockCollectByStation>();
            //第一排
            var _list = LesApiCommon.GetDataByCodeFilterForLVDeMold("-G-", data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "G排",
                bufferStockCollectByStationList = _list
            });
            //第二排
            _list = LesApiCommon.GetDataByCodeFilterForLVDeMold("-H-", data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "H排",
                bufferStockCollectByStationList = _list
            });

            return new MessageModel<List<BufferStockCollectByStationGroupCardViewModel>>()
            {
                msg = "获取成功",
                success = true,
                response = resultModelList
            };
        }


        /// <summary>
        /// 获取 高压脱模托盘区列表，为可视化页面专用
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //注意：必须要加权限，不然一直刷新但是token不延时 【Editby shaocx,2021-10-18】
        [AllowAnonymous]
        public async Task<MessageModel<List<BufferStockCollectByStationGroupCardViewModel>>> GetStockForHVDeMoldPalletVisual()
        {
            List<BufferStockCollectByStationGroupCardViewModel> resultModelList = new List<BufferStockCollectByStationGroupCardViewModel>();
            var data = await _v_LES_BufferStockCollectByStationServices.Query(x => x.StoreAreaCode == StoreAreaEnum.KCQY_TMYBKTQ.ToString());
            foreach (var item in data)
            {
                item.Station_ModifyTimeStr = DateTimeHelper.ConvertToString(item.Station_ModifyTime);
            }

            List<V_LES_BufferStockCollectByStation> newList = new List<V_LES_BufferStockCollectByStation>();
            //第一排
            var _list = LesApiCommon.GetDataByCodeFilterForLVDeMold("-I-", data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "I排",
                bufferStockCollectByStationList = _list
            });
            //第二排
            _list = LesApiCommon.GetDataByCodeFilterForLVDeMold("-J-", data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "J排",
                bufferStockCollectByStationList = _list
            });

            return new MessageModel<List<BufferStockCollectByStationGroupCardViewModel>>()
            {
                msg = "获取成功",
                success = true,
                response = resultModelList
            };
        }



        /// <summary>
        /// 获取 脱模引线接收区 库存列表，为可视化页面专用
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //注意：必须要加权限，不然一直刷新但是token不延时 【Editby shaocx,2021-10-18】
        [AllowAnonymous]
        public async Task<MessageModel<List<BufferStockCollectByStationGroupCardViewModel>>> GetStockForDeMoldLeadVisual()
        {
            List<BufferStockCollectByStationGroupCardViewModel> resultModelList = new List<BufferStockCollectByStationGroupCardViewModel>();
            var data = await _v_LES_BufferStockCollectByStationServices.Query(x => x.StoreAreaCode == StoreAreaEnum.KCQY_TMYXJSQ.ToString());
            foreach (var item in data)
            {
                item.Station_ModifyTimeStr = DateTimeHelper.ConvertToString(item.Station_ModifyTime);
            }

            List<V_LES_BufferStockCollectByStation> newList = new List<V_LES_BufferStockCollectByStation>();
            //第一列
            var _list = LesApiCommon.GetDataByCodeFilterForLVDeMold("-A-", data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "A",
                bufferStockCollectByStationList = _list
            });
            //第二列
            _list = LesApiCommon.GetDataByCodeFilterForLVDeMold("-B-", data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "B",
                bufferStockCollectByStationList = _list
            });
            //第三列
            _list = LesApiCommon.GetDataByCodeFilterForLVDeMold("-C-", data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "C",
                bufferStockCollectByStationList = _list
            });
            //第四列
            _list = LesApiCommon.GetDataByCodeFilterForLVDeMold("-D-", data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "D",
                bufferStockCollectByStationList = _list
            });
            //第五列
            _list = LesApiCommon.GetDataByCodeFilterForLVDeMold("-E-", data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "E",
                bufferStockCollectByStationList = _list
            });


            return new MessageModel<List<BufferStockCollectByStationGroupCardViewModel>>()
            {
                msg = "获取成功",
                success = true,
                response = resultModelList
            };
        }

        #endregion


        /// <summary>
        /// 获取 高压内膜准备区库存列表，为可视化页面专用
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //注意：必须要加权限，不然一直刷新但是token不延时 【Editby shaocx,2021-10-18】
        //[AllowAnonymous]
        public async Task<MessageModel<List<BufferStockCollectByStationGroupCardViewModel>>> GetStockForKCQY_GYNMZBQStockVisual()
        {
            List<BufferStockCollectByStationGroupCardViewModel> resultModelList = new List<BufferStockCollectByStationGroupCardViewModel>();
            var data = await _v_LES_BufferStockCollectByStationServices.Query(x => x.StoreAreaCode == StoreAreaEnum.KCQY_GYNMZBQ.ToString());
            foreach (var item in data)
            {
                item.Station_ModifyTimeStr = DateTimeHelper.ConvertToString(item.Station_ModifyTime);
            }

            List<V_LES_BufferStockCollectByStation> newList = new List<V_LES_BufferStockCollectByStation>();
            //第一列
            var _list = GetDataByLastIndex(1, 3, data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "1#高压绕线机",
                bufferStockCollectByStationList = _list
            });
            //第二列
            _list = GetDataByLastIndex(4, 6, data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "2#高压绕线机",
                bufferStockCollectByStationList = _list
            });
            //第三列
            _list = GetDataByLastIndex(7, 9, data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "3#高压绕线机",
                bufferStockCollectByStationList = _list
            });
            //第四列
            _list = GetDataByLastIndex(10, 12, data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "4#高压绕线机",
                bufferStockCollectByStationList = _list
            });
            //第五列
            _list = GetDataByLastIndex(13, 15, data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "5#高压绕线机",
                bufferStockCollectByStationList = _list
            });
            //第六列
            _list = GetDataByLastIndex(16, 18, data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "6#高压绕线机",
                bufferStockCollectByStationList = _list
            });
            //第七列
            _list = GetDataByLastIndex(19, 21, data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "7#高压绕线机",
                bufferStockCollectByStationList = _list
            });

            return new MessageModel<List<BufferStockCollectByStationGroupCardViewModel>>()
            {
                msg = "获取成功",
                success = true,
                response = resultModelList
            };
        }


        /// <summary>
        /// 获取 高压内膜托盘区库存列表，为可视化页面专用
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //注意：必须要加权限，不然一直刷新但是token不延时 【Editby shaocx,2021-10-18】
        [AllowAnonymous]
        public async Task<MessageModel<List<BufferStockCollectByStationGroupCardViewModel>>> GetStockForKCQY_GYNMTPQStockVisual()
        {
            List<BufferStockCollectByStationGroupCardViewModel> resultModelList = new List<BufferStockCollectByStationGroupCardViewModel>();
            var data = await _v_LES_BufferStockCollectByStationServices.Query(x => x.StoreAreaCode == StoreAreaEnum.KCQY_GYNMTPQ.ToString());
            foreach (var item in data)
            {
                item.Station_ModifyTimeStr = DateTimeHelper.ConvertToString(item.Station_ModifyTime);
            }

            List<V_LES_BufferStockCollectByStation> newList = new List<V_LES_BufferStockCollectByStation>();
            //第一列
            var _list = GetDataByLastIndex(1, 6, data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "第一列",
                bufferStockCollectByStationList = _list
            });
            //第二列
            _list = GetDataByLastIndex(7, 12, data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "第二列",
                bufferStockCollectByStationList = _list
            });
            //第三列
            _list = GetDataByLastIndex(13, 18, data);
            resultModelList.Add(new BufferStockCollectByStationGroupCardViewModel()
            {
                CardTitle = "第三列",
                bufferStockCollectByStationList = _list
            });

            return new MessageModel<List<BufferStockCollectByStationGroupCardViewModel>>()
            {
                msg = "获取成功",
                success = true,
                response = resultModelList
            };
        }

        private List<V_LES_BufferStockCollectByStation> GetDataByLastIndex(int minValue, int maxValue, List<V_LES_BufferStockCollectByStation> data)
        {
            var _list = data.Where(x =>
              Convert.ToInt32(x.StationCode.Substring(x.StationCode.Length - 2, 2)) >= minValue
              && Convert.ToInt32(x.StationCode.Substring(x.StationCode.Length - 2, 2)) <= maxValue
          ).OrderBy(x => Convert.ToInt32(x.StationCode.Substring(x.StationCode.Length - 2, 2))).ToList();
            return _list;
        }


        /// <summary> 
        /// 获取单个库存信息 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        public async Task<MessageModel<Les_StockInfo>> Get(int id = 0)
        {
            return new MessageModel<Les_StockInfo>()
            {
                msg = "获取成功",
                success = true,
                response = await _Les_StockInfoServices.QueryById(id)
            };
        }

        /// <summary> 
        /// 分拣入库 
        /// </summary> 
        /// <param name="param">要新增的库存信息对象</param> 
        /// <returns></returns> 
        [HttpPost]
        public async Task<MessageModel<bool>> Post([FromBody] InStorePostParam param)
        {
            try
            {
                #region 验证
                MessageModel<bool> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<InStorePostParam, bool>(param);
                if (retBody != null)
                {
                    return retBody;
                }

                List<ValidateModel> columnsList = null;
                columnsList = new List<ValidateModel>() {
                   new ValidateModel(){ ChinaName="站点ID", DataType=typeof(int), DataValue=param.StationId },
                   new ValidateModel(){ ChinaName="是否人工分拣入库", DataType=typeof(bool), DataValue=param.IsPersonPickInStore },
                };
                retBody = ValidateDataHelper.CommonValidate<InStorePostParam, bool>(param, columnsList);
                if (retBody != null)
                {
                    return retBody;
                }
                //*/
                #endregion

                #region 验证AGV服务是否开启
                if (param.IsPersonPickInStore == false)
                {
                    using (LesCCService.LesCCServiceClient client = new LesCCService.LesCCServiceClient())
                    {
                        LesCCService.SdaResEntity testResult = await client.TestAgvConnectionAsync();
                        if (testResult.resultk__BackingField == false)
                        {
                            return MessageModel<bool>.Fail(testResult.resMsgk__BackingField);
                        }
                    }
                }
                #endregion

                //验证站点是否能被使用
                var validateIsAllowUseResult = await _base_StationServices.ValidateStationIsAllowUse(param.StationId);
                if (!validateIsAllowUseResult.success)
                {
                    return validateIsAllowUseResult;
                }
                if (param.IsPersonPickInStore == false)
                {
                    //验证是否有可用的库存
                    var emptyStationListResult = await _base_StationServices.GetEmptyStationList(base_CodeItemsServices, StoreAreaEnum.StoreBuffer, StationPlaceTypeEnum.货物工位);
                    if (emptyStationListResult.response == null || emptyStationListResult.response.Count == 0)
                    {
                        return MessageModel<bool>.Fail("立库缓存区没有可用的空闲库位");
                    }
                }

                #region 验证用户是否登出

                var isUserLogout = LesApiCommon.IsUserLogout<bool>(_user);
                if (isUserLogout != null) return isUserLogout;

                #endregion

                var result = await _v_Les_BufferStockCollectService.InStoreForSortSuccess(param, _base_MaterialServices, _unitOfWork,
                    _base_StationServices, _user, base_CodeItemsServices, _Les_PickInStockTaskServices, _les_Mater_V_StationServices, _les_AgvTaskServices);
                if (result.success && param.IsPersonPickInStore && param.IsPickFinish)
                {
                    using (LesCCService.LesCCServiceClient client = new LesCCServiceClient())
                    {
                        LesCCService.SdaResEntity sr = await client.StockPreparationFinishNoticeWhenPersonInStoreAsync(result.response);
                        if (sr.resultk__BackingField == false)
                        {
                            return MessageModel<bool>.Fail("通知Thingwox备料完成失败:" + sr.resMsgk__BackingField);
                        }
                    }
                }
                return MessageModel<bool>.Success("成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "新增立库缓存区库存信息 出现异常:" + ex.Message);
                return MessageModel<bool>.Fail("失败:" + ex.Message);
            }
        }


        /// <summary> 
        /// 获取分组查询立库缓存区的物料列表
        /// </summary> 
        /// <param name="param">查询对象</param> 
        /// <returns>获取结果</returns> 
        [HttpPost]
        [AllowAnonymous]
        public async Task<MessageModel<List<V_BufferStockCollectGroupMaterial>>> GetBufferStockCollectGroupMaterialList([FromBody] V_BufferStockCollectGroupMaterial param)
        {
            List<V_BufferStockCollectGroupMaterial> list = null;
            list = await _V_BufferStockCollectGroupMaterialServices.Query(x => x.AllowProcedure == param.AllowProcedure
            && x.MaterialCodeItemId == param.MaterialCodeItemId);
            return new MessageModel<List<V_BufferStockCollectGroupMaterial>>()
            {
                msg = "获取成功",
                success = true,
                response = list
            };
        }


        /// <summary> 
        /// 更新库存信息 
        /// </summary> 
        /// <param name="request">要更新的库存信息对象</param> 
        /// <returns>更新结果</returns> 
        [HttpPut]
        public async Task<MessageModel<string>> Put([FromBody] Les_StockInfo request)
        {
            var data = new MessageModel<string>();
            if (request.Id > 0)
            {
                request.ModifyTime = DateTime.Now;
                request.ModifyBy = _user.Name;
                request.ModifyId = _user.ID;
                request.OperationRemark = "更新";
                data.success = await _Les_StockInfoServices.Update(request);
                if (data.success)
                {
                    data.msg = "更新成功";
                    data.response = request?.Id.ObjToString();
                }
            }

            return data;
        }

        /// <summary> 
        /// 删除库存信息 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>删除结果</returns> 
        [HttpDelete]
        public async Task<MessageModel<string>> Delete(int id = 0)
        {
            var data = new MessageModel<string>();
            if (id > 0)
            {
                var detail = await _Les_StockInfoServices.QueryById(id);
                if (detail != null)
                {
                    data.success = await _Les_StockInfoServices.DeleteById(detail.Id);
                    if (data.success)
                    {
                        data.msg = "删除成功";
                        data.response = detail?.Id.ObjToString();
                    }
                }
            }

            return data;
        }



        /// <summary> 
        /// 删除某个区域的余料和托盘信息 
        /// </summary> 
        /// <returns>删除结果</returns> 
        [HttpDelete]
        [AllowAnonymous]
        public async Task<MessageModel<bool>> DeleteAllAllEmptySalverStation(string storeAreaEnumValue,
            string remark)
        {
            if (string.IsNullOrEmpty(storeAreaEnumValue))
            {
                return MessageModel<bool>.Fail("库存区域不能为空");
            }
            StoreAreaEnum storeAreaEnum = (StoreAreaEnum)Enum.Parse(typeof(StoreAreaEnum), storeAreaEnumValue.ToString());
            return await _Les_StockInfoServices.DeleteAllSalverStation(storeAreaEnum, remark, _unitOfWork, _user, _les_PersonHandlerRecordServices, _les_InOutStockRecordServices);
        }



        /// <summary> 
        /// 删除某个区域的全部库存 
        /// </summary> 
        /// <returns>删除结果</returns> 
        [HttpDelete]
        [AllowAnonymous]
        public async Task<MessageModel<bool>> ClearStockByArea(string storeAreaEnumValue,
            string remark)
        {
            if (string.IsNullOrEmpty(storeAreaEnumValue))
            {
                return MessageModel<bool>.Fail("库存区域不能为空");
            }
            StoreAreaEnum storeAreaEnum = (StoreAreaEnum)Enum.Parse(typeof(StoreAreaEnum), storeAreaEnumValue.ToString());
            return await _Les_StockInfoServices.ClearStockByArea(storeAreaEnum, remark, _unitOfWork, _user, _les_PersonHandlerRecordServices, _les_InOutStockRecordServices);
        }


        /// <summary> 
        /// 根据站点ID删除库存 
        /// </summary> 
        /// <returns>删除结果</returns> 
        [HttpDelete]
        [AllowAnonymous]
        public async Task<MessageModel<bool>> DeleteStockByStationId(int stationId, string manualHandlerRemark)
        {
            try
            {
                //1、寻找这个站点上的库存
                V_LES_BufferStockCollect store = null;
                List<V_LES_BufferStockCollect> storeList = await _v_Les_BufferStockCollectService.Query(x => x.StationId == stationId);
                if (storeList != null && storeList.Count > 0)
                {
                    store = storeList[0];
                }
                var result = await _Les_StockInfoServices.DeleteStockByStationId(_les_AgvTaskServices, _les_PersonHandlerRecordServices, stationId, manualHandlerRemark, _unitOfWork, _user, _les_InOutStockRecordServices);
                if (result.success && store != null)
                {
                    using (LesCCService.LesCCServiceClient client = new LesCCService.LesCCServiceClient())
                    {
                        SdaResEntity sdaRes = null;
                        sdaRes = await client.StockPreparationFinishNoticeWhenClearAsync(store.BurdenWorkNo, stationId, manualHandlerRemark);
                        if (sdaRes.resultk__BackingField)
                        {
                            return MessageModel<bool>.Success("成功");
                        }
                        else
                        {
                            return MessageModel<bool>.Fail(sdaRes.resMsgk__BackingField);
                        }
                    }
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError("根据站点ID删除库存 出现异常,ex:" + JsonConvert.SerializeObject(ex));
                return MessageModel<bool>.Fail("根据站点ID删除库存 出现异常:" + ex.Message);
            }
        }
    }
}
